<?php
require_once "lib/Func.php";
require_once "data/dao/GameDAO.php";
require_once "services/AWSProxy.php";
require_once "data/dao/CollectionDAO.php";
require_once "data/dao/WishListDAO.php";
require_once "data/dao/FriendCodeDAO.php";
require_once "data/dao/UserDAO.php";
require_once "application/user/Friend.php";

class GameRenderer extends Func_Controller{
	
	protected $view = "game.tpl";
	
	private $game;
	
	private $user;
	
	public function GameRenderer($gameId){
		
		$facebook = new FacebookProxy();
		$this->user = $facebook->requireLogin();

		Validate::notNull($gameId);
		
		$gdao = new GameDAO();
		$this->game = $gdao->getGame($gameId);
		
		parent::__construct();
	}
		
	protected function render(){
		
		$this->value("styleSheet", file_get_contents("html/wiiSocial.css"));
		$this->smarty->assign("javaScript", file_get_contents("html/wiiSocial.js"));
		
		$this->value("HOST", HOST_URL);
		
		$this->value("game", $this->game);
		
		$aws = new AWSProxy();
		$this->value("price", $aws->getItemPrice($this->game->getID()));
		
		$cdao = new CollectionDAO();
		$this->value("numberOfPlayers", $cdao->getNumberOfCollectionsContainingGame($this->game->getID()));
		
		$wdao = new WishListDAO();
		$this->value("numberOfWishlists", $wdao->getNumberOfWishListsContainingGame($this->game->getID()));
		
		
		$this->value("friends", $this->getPlayersThatHaveThisGame());
		
		// if true, page will default to the friend codes view
		$this->value("showFriends", (HTTPRequest::getParam("view") == "friends"));
	}
	
	private function getPlayersThatHaveThisGame(){
		
		$fdao = new FriendCodeDAO();
		$f = $fdao->findFriendsForGame($this->game->getID(), $this->user,
			$this->game->getTitle(), null);

		if($f == null){
			return null;
		}
		
		$friendIds = $f->getFriends();
		$friends = array();
		
		$udao = new UserDAO();
		
		foreach ($friendIds as $fi){
			$uid = $fi['user_id'];
			// get user
			$u = $udao->findUser($uid);
			
			// get users friend code
			$friendCode = $fdao->findFriendCode($uid, $this->game->getID());
			
			array_push($friends, new Friend($uid, $u->getFirstName(), $u->getLastName(), $u->getProfilePicSmallUrl(),
				$u->getProfilePicBigUrl(), $u->getWiiCode(), $u->getLocationString(), $u->getStoreLocation(),
				array("friendCode" => $friendCode), null));
		}
		
		return $friends;
	}
}
$g = new GameRenderer(HTTPRequest::getParam("game-id"));
?>
